package com.techie.mdm.appbar.showcase.binding;

import org.springframework.binding.value.ValueModel;
import org.springframework.binding.value.support.AbstractDerivedValueModel;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;

/**
 * Like MessageFormatValueModel, but allows setting the format.
 */
public class DynamicMessageFormatValueModel extends AbstractDerivedValueModel
{
    static public final String PATTERN = "pattern";

    private String pattern;

    private final ValueModel[] argumentValueModels;

    private String value;

    /**
     * Constructs a new MessageFormatValueModel with a single argument.
     * @param pattern the pattern
     * @param argumentValueModel the single value model holding the
     * value to be formatted and substituted
     */
    public DynamicMessageFormatValueModel(String pattern, ValueModel argumentValueModel) {
        this(pattern, new ValueModel[] {argumentValueModel});
    }

    /**
     * Constructs a new MessageFormatValueModel with a group of arguments.
     * @param pattern the pattern
     * @param argumentValueModels an array of value models holding the
     * value to be formatted and substituted
     */
    public DynamicMessageFormatValueModel(String pattern, ValueModel[] argumentValueModels) {
        super((ValueModel[])new HashSet(Arrays.asList(argumentValueModels)).toArray(new ValueModel[0]));
        this.pattern = pattern;
        this.argumentValueModels = argumentValueModels;
        // prime the initial value
        sourceValuesChanged();
    }

    protected void sourceValuesChanged() {
        String oldValue = value;
        value = MessageFormat.format(pattern, getArgumentValues());
        fireValueChange(oldValue, value);
    }

    public Object getValue() {
        return value;
    }

    private Object[] getArgumentValues() {
        Object[] values = new Object[argumentValueModels.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = argumentValueModels[i].getValue();
        }
        return values;
    }

    public String getPattern()
    {
        return pattern;
    }

    public void setPattern(String pattern)
    {
        if (!pattern.equals(this.pattern))
        {
            this.pattern = pattern;
            sourceValuesChanged();
        }
    }


}
